package com.lineage.server.utils;

import com.lineage.server.templates.L1NewMap;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class NewMapUtil {
  private static ConcurrentHashMap<Integer, ArrayList<L1NewMap>> M = new ConcurrentHashMap<>();
  
  public static void load(String path) throws IOException {
    File f = new File(path);
    if (!f.isDirectory() || !f.exists())
      throw new NullPointerException("错误的地图路径或地图不存在！"); 
    FileChannel fc = null;
    File[] listFiles;
    int length = (listFiles = f.listFiles(new FileFilter() {
          public final boolean accept(File pathname) {
            return pathname.isDirectory();
          }
        })).length;
    int i = 0;
    while (i < length) {
      File map = listFiles[i];
      int mapId = 0;
      try {
        mapId = Integer.parseInt(map.getName());
      } catch (NumberFormatException numberFormatException) {}
      ArrayList<L1NewMap> maps = new ArrayList<>();
      M.put(Integer.valueOf(mapId), maps);
      File[] listFiles2;
      int length2 = (listFiles2 = map.listFiles(new FileFilter() {
            public final boolean accept(File pathname) {
              return (pathname.isFile() && pathname.getName().toLowerCase().endsWith(".bin"));
            }
          })).length;
      int j = 0;
      while (j < length2) {
        File fileMap = listFiles2[j];
        ByteBuffer buf = ByteBuffer.allocate(4096);
        fc = (new FileInputStream(fileMap)).getChannel();
        fc.read(buf);
        fc.close();
        int x = Integer.parseInt(fileMap.getName().substring(0, 4), 16) & 0xFFFF;
        int y = Integer.parseInt(fileMap.getName().substring(4, 8), 16) & 0xFFFF;
        maps.add(new L1NewMap(x, y, buf.array()));
        j++;
      } 
      i++;
    } 
    System.out.println(String.valueOf(String.valueOf(NewMapUtil.class.getName())) + ": 加载 " + M.size() + " 张地图。");
  }
  
  public static ArrayList<L1NewMap> getBlock(int mapId) {
    if (M.containsKey(Integer.valueOf(mapId)))
      return M.get(Integer.valueOf(mapId)); 
    return null;
  }
}
